package com.yonyou.hxjy.service.dingtalk.Impl.dintalkgetImpl;

import com.yonyou.hxjy.entity.DingtalkTokenDto;
import com.yonyou.hxjy.enums.*;
import com.yonyou.hxjy.service.dingtalk.DingtalkAccessTokenGetService;
import com.yonyou.hxjy.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Service
public class DingtalkAccessTokenGetServiceImpl implements DingtalkAccessTokenGetService {

    @Value("${dingtalk_appkey}")
    private String appkey;

    @Value("${dingtalk_appSercet}")
    private String appSercet;
    @Autowired
    private RestTemplate restTemplate;
    private static final long EXPIRE_OFFSET = 60;   // 提前 60 s 失效
    private final Lock lock = new ReentrantLock();



//    @Override
//    // 获取token
//    public String getAppToken(String tenantId) {
//        String redisKey = "ywDingTalkTest" + tenantId;
//        String token = (String) RedisUtils.get(redisKey);
//        System.out.println(token);
//        if (StringUtils.isEmpty(token)) {
//            //CenterOauth2TenantConfig config = configService.getConfig(tenantId, CenterConfigConst.DINGTALK);
//            //Objects.requireNonNull(config, String.format("钉钉平台 当前%s租户未设置通讯录 app信息", tenantId));
//            String url = String.format(DingtalkConstant.GET_TOKEN, appkey, appSercet);
//
//            DingtalkTokenDto tokenDto = restTemplate.getForObject(url, DingtalkTokenDto.class);
//            Integer errcode = tokenDto.getErrcode();
//            if (errcode != 0) {
//                throw new RuntimeException(String.format("当前%s租户 请求钉钉平台token接口报错", tenantId));
//            }
//
//            token = tokenDto.getAccess_token();
//            RedisUtils.set(redisKey, token, tokenDto.getExpires_in());
//        }
//        return token;
//    }
        public String getAppToken(String tenantId) {
            String redisKey = "ywDingTalkTest" + tenantId;
            String token = (String) RedisUtils.get(redisKey);
            Long ttl = RedisUtils.getExpire(redisKey);
            if (token == null || ttl == null || ttl < EXPIRE_OFFSET) {
                lock.lock();
                try {
                    // 二次检查
                    token = (String) RedisUtils.get(redisKey);
                    ttl = RedisUtils.getExpire(redisKey);
                    if (token == null || ttl == null || ttl < EXPIRE_OFFSET) {
                        String url = String.format(DingtalkConstant.GET_TOKEN, appkey, appSercet);
                        DingtalkTokenDto tokenDto = restTemplate.getForObject(url, DingtalkTokenDto.class);
                        Integer errcode = tokenDto.getErrcode();
                        if (errcode != 0) {
                            throw new RuntimeException(String.format("当前%s租户 请求钉钉平台token接口报错", tenantId));
                        }
                        token = tokenDto.getAccess_token();
                        RedisUtils.set(redisKey, token, tokenDto.getExpires_in());      // 真正请求钉钉
                    }
                } finally {
                    lock.unlock();
                }
            }
            return token;
        }

}
